package com;

import javax.xml.bind.DatatypeConverter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Scanner;

public class ReturnDigest extends Thread {

    private String fileName;

    private byte[] result = null;

    public ReturnDigest(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public void run(){

        try {

            FileInputStream in = new FileInputStream(fileName);

            MessageDigest sha = MessageDigest.getInstance("SHA-256");

            DigestInputStream digestInputStream = new DigestInputStream(in,sha);

            while (digestInputStream.read() != -1) ;

            digestInputStream.close();

            result = sha.digest();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public byte[] returnByte(){

        return result;

    }

    /**
     * 轮询解决
     * @param args
     */
    public static void main(String[] args) {

        ReturnDigest[] returnDigests = new ReturnDigest[args.length];

        for(int i=0;i<args.length;i++){

            returnDigests[i] = new ReturnDigest(args[i]);

            returnDigests[i].start();

        }

        for(int i=0;i<args.length;i++){

            while (true){

                byte[] res = returnDigests[i].returnByte();

                if(res != null){

                    StringBuilder sb = new StringBuilder(args[i]);

                    sb.append(": ");

                    sb.append(DatatypeConverter.printHexBinary(res));

                    System.out.println(sb);

                    break;

                }

            }

        }

    }

    /**
     * 通过yield解决
     */
    /*public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        while (in.hasNext()){

            String fileName = in.next();

            ReturnDigest returnDigest = new ReturnDigest(fileName);

            returnDigest.start();

            try {

                returnDigest.join();

                byte[] res = returnDigest.returnByte();

                StringBuilder sb = new StringBuilder(fileName);

                sb.append(": ");

                sb.append(DatatypeConverter.printHexBinary(res));

                System.out.println(sb);

            } catch (InterruptedException e) {
                e.printStackTrace();
            }


        }

    }*/

}
